﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Celf;
//using Apollo ;
//using LuaInterface;

/// <summary>
/// 打开WebView窗口 
/// NOTE: 全局只存在一个全屏的窗口 , 如果想使用多个网页窗口内嵌代码需要修改
/// </summary>
class WebViewService: Singleton<WebViewService>
{
    private UniWebView mCurrentView;

    private bool mIsLoading = false;
    private bool mIsVisible = false;
    private string mCurUrl = "";

    /// <summary>
    /// 初始化
    /// </summary>
    protected override void OnInit()
    {
        Create();
    }
    
    /// <summary>
    /// 销毁
    /// </summary>
    protected override void OnRelease()
    {
        Destroy();
    }
    
    //打开Url，默认全屏
    public void Open(string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return;
        }

        // 防止连续打开同一个页面
        if (mIsLoading && mCurUrl == str)
        {
            return;
        }


        DebugLog("Open Start, Url: " + str);

        mIsLoading = true;
        mCurUrl = str;

        Create();
        mCurrentView.Load(str);


        //LuaService.Instance.FireEvent("OnWebViewVisible" , false);
    }

    //关闭Url
    public void Close()
    {
        if (null == mCurrentView)
        {
            return;
        }

        mIsLoading = false;
        mCurUrl = "";
        while (mCurrentView.CanGoBack())
        {
            mCurrentView.GoBack();
        }
        SetVisible(false);
        
        mCurrentView.CleanCache();
        mCurrentView.CleanCookie();

       // LuaService.Instance.FireEvent("OnWebViewVisible", true);
    }

    /// <summary>
    /// 向Js层发送数据，JS层需实现接口:OnReceivedMessageFromUnity(string cmd, string json)
    /// 参数格式：Json格式, {"paramname1":"value1", "paramname2":"value2"}
    /// </summary>
    public void SendCommondToJs(string cmd, Dictionary<string,string> parameters  )
    {
        if (string.IsNullOrEmpty(cmd))
        {
            return;
        }

        if (null == mCurrentView)
        {
            return;
        }

        string jsStr = Convert2JsonStr(cmd,parameters);
        DebugLog("CmdParam:" + jsStr);
        mCurrentView.EvaluatingJavaScript(jsStr);
    }

    private string Convert2JsonStr(string cmd, Dictionary<string, string> parameters)
    {
        string paramsStr = "{";
        List<string> keys = parameters.Keys.ToList();
        for (int i = 0; i < keys.Count; i++)
        {
            string key = keys[i];
            string value = parameters[key];

            string param = "\"" + key + "\":\"" + value + "\",";
            paramsStr += param;
        }
        paramsStr += "}";

        string jsStr = "OnReceivedMessageFromUnity(\"" + cmd + "\"," + paramsStr + ")";
        return jsStr;
    }


    private void Create()
    {
        mCurrentView = gameObject.GetComponent<UniWebView>();

        if (null == mCurrentView)
        {
            mCurrentView = gameObject.AddComponent<UniWebView>();

            mCurrentView.loadOnStart = false;
            mCurrentView.autoShowWhenLoadComplete = false;

            mCurrentView.OnLoadComplete += OnLoadComplete;
            mCurrentView.OnReceivedMessage += OnReceivedMessage;
            mCurrentView.OnEvalJavaScriptFinished += OnEvalJavaScriptFinished;
            mCurrentView.OnReceivedKeyCode += OnReceivedKeyCode;
            mCurrentView.OnWebViewShouldClose += OnWebViewShouldClose;
            mCurrentView.insets = new UniWebViewEdgeInsets(0, 0,500, 0);
        }

        SetVisible(false);

        DebugLog("CreateWebView");
    }

    private void Destroy()
    {
        mCurrentView = gameObject.AddComponent<UniWebView>();
        if (null != mCurrentView)
        {
            mCurrentView.OnLoadComplete -= OnLoadComplete;
            mCurrentView.OnReceivedMessage -= OnReceivedMessage;
            mCurrentView.OnEvalJavaScriptFinished -= OnEvalJavaScriptFinished;
            mCurrentView.OnReceivedKeyCode -= OnReceivedKeyCode;
            mCurrentView.OnWebViewShouldClose -= OnWebViewShouldClose;
            SetVisible(false); 
            mCurrentView.CleanCache();
            Destroy(mCurrentView);
            mCurrentView = null;
        }
        DebugLog("DestroyWebView");
    }

    private void SetVisible(bool visible)
    {
        if (mIsVisible == visible)
        {
            return; 
        }


        DebugLog("SetVisible:" + visible);
        mIsVisible = visible;
        if (visible)
        {
            mCurrentView.Show();
        }
        else
        {
            mCurrentView.Hide();
        }
    }

    //是否现在工具条（仅限IOS）
    private void SetToolBarVisible(bool visible , bool animation = false)
    {
        if (null == mCurrentView)
        {
            return;
        }
        if (true == visible)
        {
            mCurrentView.ShowToolBar(animation);
        }
        else
        {
            mCurrentView.HideToolBar(animation);
        }
    }

    /// <summary>
    /// WebView将要关闭时回调，返回true则直接关闭，返回false则不关闭
    /// </summary>
    private bool OnWebViewShouldClose(UniWebView webView)
    {
        DebugLog("##############################OnWebViewShouldClose");
        return true;
    }

    /// <summary>
    /// 加载一个Url完成反馈，不仅仅限于主动加载的URL，包含页面中加载的url
    /// </summary>
    void OnLoadComplete(UniWebView webView, bool success, string errorMessage)
    {
        DebugLog("OnLoadComplete, success:" + success + ",errorMessage:" + errorMessage);

        if (success)
        {
            if (mIsLoading)
            {
                DebugLog("OnLoadComplete success , SetVisible true");

                mIsLoading = false;
                SetVisible(true);
            }
        }
        else
        {
            DebugLog("Something wrong in webview loading: " + errorMessage);
        }
    }

    /// <summary>
    /// 执行一段JS脚本结束回调
    /// </summary>
    void OnEvalJavaScriptFinished(UniWebView webView, string r)
    {
        Debug.Log("OnEvalJavaScriptFinished：" + r);
    }
    /// <summary>
    /// 接收到JS数据
    /// 消息格式："uniwebview://cmdName?param1=value1&param2=value2"
    /// </summary>
    private void OnReceivedMessage(UniWebView webView, UniWebViewMessage message)
    {
        DebugLog("OnReceivedMessage Cmd:" + message.path);
        WebViewParser.testParseCmdFromJs(message.path);
    }

    /// <summary>
    /// 接收键盘（Android）按键反馈
    /// </summary>
    private void OnReceivedKeyCode(UniWebView webView, int keyCode)
    {
        DebugLog("OnReceivedKeyCode:" + keyCode);
        if (keyCode == 4)
        {
            DebugLog("OnReceivedKeyCode________________Close");
            Close();
        }
    }

    public void DebugLog(string str)
    {
        Debug.Log("UniWebView #WebViewService#" + str);
    }

    private bool isNeedResume = false;

    void OnApplicationPause(bool pauseStatus)
    {
        if (pauseStatus == true)
        {
            if (mIsVisible)
            {
                mCurrentView.Hide();
                isNeedResume = true;
            }
        }
        else
        {
            if (isNeedResume)
            {
                mCurrentView.Show();
            }
            isNeedResume = false;
        }
    }
}
